//
//  Fraction.m
//  02-ClassAndObject
//
//  Created by 曹曹 on 16/7/5.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "Fraction.h"

@implementation Fraction
- (instancetype)initWithNumerator:(NSInteger)nume denominator:(NSInteger)denom {
    self = [super init];
    if (self) {
        _numerator = nume;
        _demoninator = denom;
    }
    return self;
}
+ (instancetype)fractionWithNumerator:(NSInteger)nume denominator:(NSInteger)denom {
    return [[Fraction alloc] initWithNumerator:nume denominator:denom];
}
- (Fraction *)plusWithFraction:(Fraction *)frac {
    NSInteger newNumerator = self.numerator * frac.demoninator + self.demoninator * frac.numerator;
    NSInteger newDonominator = self.demoninator * frac.demoninator;
    Fraction *newFrac = [Fraction fractionWithNumerator:newNumerator denominator:newDonominator];
    if (newDonominator == 0) {
        NSLog(@"分母不能为0");
        return nil;
    } else {
        [newFrac reduce];
        return newFrac;
    }
}
- (Fraction *)decreaseWithFraction:(Fraction *)frac {
    NSInteger newNumerator = self.numerator * frac.demoninator - self.demoninator * frac.numerator;
    NSInteger newDonominator = self.demoninator * frac.demoninator;
    Fraction *newFrac = [Fraction fractionWithNumerator:newNumerator denominator:newDonominator];
    if (newDonominator == 0) {
        NSLog(@"分母不能为0");
        return nil;
    } else {
        [newFrac reduce];
        return newFrac;
    }
}
- (Fraction *)multipleWithFraction:(Fraction *)frac {
    NSInteger newNumerator = self.numerator * frac.numerator;
    NSInteger newDonominator = self.demoninator * frac.demoninator;
    Fraction *newFrac = [Fraction fractionWithNumerator:newNumerator denominator:newDonominator];
    if (newDonominator == 0) {
        NSLog(@"分母不能为0");
        return nil;
    } else {
        [newFrac reduce];
        return newFrac;
    }
}
- (Fraction *)divideWithFraction:(Fraction *)frac {
    NSInteger newNumerator = self.numerator * frac.demoninator;
    NSInteger newDonominator = self.demoninator * frac.numerator;
    Fraction *newFrac = [Fraction fractionWithNumerator:newNumerator denominator:newDonominator];
    [newFrac reduce];
    return newFrac;
}
- (Fraction *)reduction {
    [self reduce];
    return self;
}
- (void)compareWithFraction:(Fraction *)frac {
    Fraction *newFrac = [self decreaseWithFraction:frac];
    if (newFrac.numerator * newFrac.demoninator > 0) {
        NSLog(@"大于");
    } else if (newFrac.numerator * newFrac.demoninator < 0) {
        NSLog(@"小于");
    } else if (newFrac.demoninator == 0) {
        NSLog(@"分母不能为0");
    }
    else {
        NSLog(@"相等");
    }
}

- (void)reduce {
    long n = self.numerator;
    long m = self.demoninator;
    long temp = 0;
    if (m == 0) {
        return;
    } else {
        while (n % m != 0) {
            temp = n % m;
            n = m;
            m = temp;
        }
        self.numerator /= m;
        self.demoninator /= m;
    }
}
@end
